<template>
  <div class="student-management">
    <el-card class="box-card" shadow="always">
      <div slot="header" class="clearfix">
        <span>学生管理</span>
        <el-button type="primary" size="small" class="float-right" @click="openDialog">
          添加学生
        </el-button>
      </div>
      <!-- 查询条件 -->
      <el-form inline class="search-form" :model="searchForm">
        <el-form-item label="姓名/学号">
          <el-input v-model="searchForm.search" placeholder="请输入关键词"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="searchForm.class_name" placeholder="选择班级" clearable>
            <el-option v-for="item in classes" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchStudents">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 学生列表 -->
      <el-table :data="studentList" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="studentId" label="学号" width="100" />
        <el-table-column prop="class_name" label="班级" width="120" />
        <el-table-column prop="dorm_id" label="宿舍号" width="100" />
        <el-table-column prop="contact" label="联系方式" width="150" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="mini" type="primary" @click="editStudent(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteStudent(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="page"
          :page-size="size"
          :total="total"
          @current-change="handlePageChange"
      />
    </el-card>
    <!-- 添加/编辑学生弹框 -->
    <el-dialog title="学生信息" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="form.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="form.class_name" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="宿舍号">
          <el-input v-model="form.dorm_id" placeholder="请输入宿舍号" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      studentList: [],
      total: 0,
      page: 1,
      size: 10,
      searchForm: {
        search: '',
        class_name: '',
      },
      dialogVisible: false,
      form: {
        id: null,
        name: '',
        studentId: '',
        class_name: '',
        dorm_id: '',
        contact: '',
      },
      classes: ['计本2班', '网络一班'], // 示例班级，可动态获取
    };
  },
  methods: {
    async fetchStudents() {
      const { search, class_name } = this.searchForm;
      const response = await axios.get('http://localhost:3000/students', {
        params: { page: this.page, size: this.size, search, class_name },
      });
      this.studentList = response.data.data;
      this.total = response.data.total;
    },
    resetSearch() {
      this.searchForm = { search: '', class_name: '' };
      this.fetchStudents();
    },
    handlePageChange(page) {
      this.page = page;
      this.fetchStudents();
    },
    openDialog() {
      this.dialogVisible = true;
      this.form = { id: null, name: '', studentId: '', class_name: '', dorm_id: '', contact: '' };
    },
    editStudent(student) {
      this.dialogVisible = true;
      this.form = { ...student };
    },
    saveStudent() {
      const method = this.form.id ? 'put' : 'post';
      const url = this.form.id ? `http://localhost:3000/students/${this.form.id}` : 'http://localhost:3000/students';
      axios[method](url, this.form).then(() => {
        this.dialogVisible = false;
        this.fetchStudents();
        this.$message({
          message: this.form.id ? '编辑成功！' : '添加成功！',
          type: 'success',
        });
      }).catch(() => {
        this.$message({
          message: '操作失败，请稍后重试。',
          type: 'error',
        });
      });
    },
    deleteStudent(id) {
      this.$confirm('此操作将永久删除该学生信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            axios.delete(`http://localhost:3000/students/${id}`).then(() => {
              this.fetchStudents();
              this.$message({
                message: '删除成功！',
                type: 'success',
              });
            });
          })
          .catch(() => {
            this.$message({
              message: '已取消删除操作',
              type: 'info',
            });
          });
    },
  },
  mounted() {
    this.fetchStudents();
  },
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.float-right {
  float: right;
}
</style>
